﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using AppKit;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.EMMA;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Wordprocessing;
//using DocumentFormat.OpenXml.Spreadsheet;
//using ExcelDataReader;
//using Ev_ExcelStandard;
using Foundation;
using static Ev_ExcelToSringsForMac.Common.Models;

namespace Ev_ExcelToSringsForMac
{
	public partial class ViewController : NSViewController
	{
		public ViewController (IntPtr handle) : base (handle)
		{
		}

        string[] strKeyPreList;

        public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

            // Do any additional setup after loading the view.


            this.Title = "Excel语言包转换工具";

            btnChooseExcel.Title = "选择Excel";
			labelExcelPath.StringValue = "";
            labellanguagePath.StringValue = "";
            //txtKeyId.StringValue = "信号名称KEY/NAME";
            //txtLanguage.StringValue = "中文_zh";
        }

        public override NSObject RepresentedObject {
			get {
				return base.RepresentedObject;
			}
			set {
				base.RepresentedObject = value;
				// Update the view, if already loaded.
			}
		}

        partial void btnStartAction(AppKit.NSButton sender) {
            this.txtDes.StringValue = "";
            if (string.IsNullOrEmpty(this.labelExcelPath.StringValue)) {
                this.addMsg("请正确选择Excel文件");
                return;
            }
            var strLastExt = this.labelExcelPath.StringValue.Substring(this.labelExcelPath.StringValue.Length - 4, 4);
            if (strLastExt != "xlsx")
            {
                addMsg("请选择Excel 以 xlsx结尾的文件.（本地另存为xlsx文件）");
                return;
            }


            var strKeyId = this.txtKeyId.StringValue;
            var strKeyLanguage = this.txtLanguage.StringValue;
            if (string.IsNullOrEmpty(strKeyId) || string.IsNullOrEmpty(strKeyLanguage))
            {
                this.addMsg("请正确输入KeyId或语言包的首行Title");
                return;
            }
            var strLocalizablePath = this.labellanguagePath.StringValue;
            if (string.IsNullOrEmpty(strLocalizablePath))
            {
                this.addMsg("请正确选择语言包文件");
                return;
            }

            /// 获取预设key值
            strKeyPreList = this.txtKeyPre.StringValue.Split(",");

            var list = ReadExcel(this.labelExcelPath.StringValue, strKeyId, strKeyLanguage);
            if (list == null)
            {
                //addMsg("读取Excel失败");
                return;
            }
            // 获取Excel
            //var list = readSheet(sheet, strKeyId,strKeyLanguage);

            //// 获取Sheet KeyValue语言包的数据
            //var list = EvExcelConvertStrings.readSheet(sheet, strKeyId, strKeyLanguage);

            //// 获取语言包文件
            var strLanguageContent = readLanguageFile(strLocalizablePath);
            if (strLanguageContent == null)
            {
                return;
            }
            //// 设置语言包Value值
            var content = setLanguageContent(strLanguageContent, list);

            //// 保存语言包文件
            saveLanguageFile(strLocalizablePath, content);
            //// 已完成
            this.addMsg("转换完成。 谢谢使用！ \r\n按任意键继续使用：Enter Key");

        }

        List<modelKeyValue> ReadExcel(string filePath, string keyId, string value)
        {
            List<modelKeyValue> list = new List<modelKeyValue>();
            SheetData sheetData;
            using (MemoryStream mem = new MemoryStream())
            {
                //using (var temp = File.OpenRead(filePath))
                //{
                //    temp.CopyTo(mem);
                //}
                try
                {

                    using (SpreadsheetDocument doc = SpreadsheetDocument.Open(filePath, false))
                    {
                        WorkbookPart wbPart = doc.WorkbookPart;
                        Worksheet worksheet = wbPart.WorksheetParts.First().Worksheet;
                        sheetData = worksheet.GetFirstChild<SheetData>();
                        Row[] rows = sheetData.Descendants<Row>().ToArray();

                        var sString = rows[0].Elements<Cell>().Where(x => GetCellValue(doc, x) == keyId).FirstOrDefault();
                        if (sString == null)
                        {
                            addMsg("Excel keyId 错误，请重新开始转换流程");
                            return null;
                        }
                        var cellKeyIdIndex = Convert.ToInt32(sString.InnerText);
                        var cellKeyValueIndex = Convert.ToInt32(rows[0].Elements<Cell>().Where(x => GetCellValue(doc, x) == value).First().InnerText);


                        if (cellKeyIdIndex < 0 || cellKeyValueIndex < 0)
                        {
                            addMsg("Excel keyId 或 语言Value 的title值错误，请重新开始转换流程");
                            return null;
                        }

                        //// 开始获取每一行的数据
                        for (int i = 1; i <= rows.Count() - 1; i++)
                        {
                            var row = rows[i];
                            if (row == null) continue;


                            var strKey = GetCellValue(doc, (Cell)row.ChildElements[cellKeyIdIndex]);
                            if (cellKeyValueIndex > row.ChildElements.Count - 1)
                            {
                                continue;
                            }
                            var strValue = GetCellValue(doc, (Cell)row.ChildElements[cellKeyValueIndex]);

                            if (string.IsNullOrWhiteSpace(strValue)) continue;

                            if (!isRepleace(strKey)) continue;

                            modelKeyValue dict = new modelKeyValue
                            {
                                strKey = strKey,
                                strValue = strValue
                            };
                            list.Add(dict);
                        }

                        doc.Close();
                    }
                }
                catch (Exception ex)
                {
                    addMsg("错误：" + ex.Message);
                    return null;
                }
                mem.Close();
            }

            return list;
        }
        public string GetCellValue(SpreadsheetDocument document, Cell cell)
        {
            SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;
            string value = cell.CellValue?.InnerXml;

            if (cell.DataType != null && (cell.DataType.Value == CellValues.SharedString || cell.DataType.Value == CellValues.String || cell.DataType.Value == CellValues.Number))
            {
                return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
            }
            else  //浮点数和日期对应的cell.DataType都为NULL
            {
                // DateTime.FromOADate((double.Parse(value)); 如果确定是日期就可以直接用过该方法转换为日期对象，可是无法确定DataType==NULL的时候这个CELL 数据到底是浮点型还是日期.(日期被自动转换为浮点
                return value;
            }
        }


        partial void btnChooseExcelAction(AppKit.NSButton sender)
        {

            var openPanel = NSOpenPanel.OpenPanel;
            openPanel.CanChooseDirectories = true;
            openPanel.CanChooseFiles = true;
            openPanel.AllowsMultipleSelection = false;
            var finded = openPanel.RunModal();
            if (finded == 1)
            {
                var excelPath = openPanel.Url.Path;

                NSFileManager.DefaultManager.FileExists(excelPath);
                labelExcelPath.StringValue = excelPath;
            }

        }

        partial void btnChooseLanguagePathAction(AppKit.NSButton sender)
        {
            var openPanel = NSOpenPanel.OpenPanel;
            openPanel.CanChooseDirectories = true;
            openPanel.CanChooseFiles = true;
            openPanel.AllowsMultipleSelection = false;
            var finded = openPanel.RunModal();
            if (finded == 1)
            {
                var path = openPanel.Url.Path;

                NSFileManager.DefaultManager.FileExists(path);
                labellanguagePath.StringValue = path;
            }
        }

        void addMsg(string msg) {
            this.txtDes.StringValue = msg + "\r\n " + this.txtDes.StringValue;
        }


        #region iOS Language File

        public void saveLanguageFile(string filePath, string content)
        {
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            //文本读取器
            using (FileStream fs = new FileStream(filePath, FileMode.CreateNew))
            {
                //【2】保存内容到txt
                StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                sw.WriteLine(content);
                sw.Flush();
                sw.Close();
            }
        }

        /// <summary>
        /// 是否判断预设值：是，则验证。
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool isRepleace(string key) {

            if (strKeyPreList.Length > 0) {
                var isResult = strKeyPreList.Contains(key);
                return isResult;
            }
            return true;
        }

        /// <summary>
        /// 设置iOS语言包文件值
        /// </summary>
        /// <param name="content"></param>
        /// <param name="list"></param>
        public string setLanguageContent(string content, List<modelKeyValue> list)
        {

            List<modelLanguageKeyValueStr> listModel = new List<modelLanguageKeyValueStr>();
            var languageList = content.Split("\";");
            foreach (var strLanguage in languageList)
            {
                var model = new modelLanguageKeyValueStr();
                model.strLanguage = strLanguage;

                var keyValue = strLanguage.Split("=");
                if (keyValue.Length != 2)
                {
                    // 如果有多个 = 等号存在
                    // 后面再写
                    continue;
                }
                model.strKey = keyValue[0].Trim();
                model.strValue = keyValue[1].TrimStart();
                listModel.Add(model);
            }

            foreach (var dict in list)
            {
                var model = listModel.Find(x => {
                    return x.strKey == $"\"{dict.strKey}\"";
                });
                /// 如果已存在Key ，则替换
                if (model != null)
                {
                    var oldStrValue = $"{model.strValue}";
                    var newStrValue = $"\"{dict.strValue}";
                    var newStrReplace = model.strLanguage.Replace(oldStrValue, newStrValue);
                    content = content.Replace(model.strLanguage, newStrReplace);

                    addMsg($">>>>>修改：{model.strKey}");
                }
                else
                {
                    /// 否则新增
                    content += $"\n\"{dict.strKey}\" = \"{dict.strValue}\";";
                    addMsg($"=====新增：{model.strKey}");
                }
            }

            return content;
        }

        /// <summary>
        /// 读取iOS语言包文件内容
        /// </summary>
        /// <param name="strLanguagePath"></param>
        /// <returns></returns>
        public string readLanguageFile(string strLanguagePath)
        {

            if (!File.Exists(strLanguagePath))
            {
                return "";
            }
            //文本读取器
            using (TextReader reader = new StreamReader(strLanguagePath, System.Text.Encoding.UTF8))
            {
                var strLocalizableStr = "";
                //一次性读完
                strLocalizableStr = reader.ReadToEnd();
                return strLocalizableStr;
            }

        }

        #endregion

    }
}
